package com.twu.biblioteca.ui;

import com.twu.biblioteca.data.Book;
import com.twu.biblioteca.data.BookDAO;
import com.twu.biblioteca.exceptions.BookOperationException;

/**
 * Created by florian on 26/12/13.
 */
public abstract class ControllerWithBook implements ScreenController{
    protected final BibliotecaUI ui;
    protected final ScreenControllerFactory controllerFactory;
    protected final BookDAO bookDAO;

    public ControllerWithBook(ScreenControllerFactory controllerFactory, BibliotecaUI ui, BookDAO bookDAO) {
        this.ui = ui;
        this.controllerFactory = controllerFactory;
        this.bookDAO = bookDAO;
        showUsage();

    }

    @Override
    public ScreenController processCommand(String line) {
        try {
            int bookId = Integer.parseInt(line);
            Book book = bookDAO.findBookForId(bookId);
            if (book!=null) {
                try {
                    return handleWithBook(book);
                } catch (BookOperationException e) {
                    return handleError();
                }
            }else {
                return handleError();

            }
        } catch (NumberFormatException e) {
            return handleError();
        }
    }

    protected abstract void showUsage();

    protected abstract ScreenController handleWithBook(Book book) throws BookOperationException;

    protected abstract ScreenController handleError();
}
